/*
 * hd44780_private.c
 *
 *  Created on: Aug 10, 2009
 *      Author: tron
 */

#include <inttypes.h>
#include "WProgram.h"
#include "HD44780.h"
#include "hd44780_private.h"

void lcd_parseStr(LCD *l, const char *chArray){
	  while (*chArray)
	    lcd_writeChar(l, *chArray++);
}

void lcd_sendRaw(LCD *l, uint8_t val, uint8_t rs_mode){
	digitalWrite(l->rs_pin, rs_mode);
	digitalWrite(l->rw_pin, LOW);

	if (l->bitmode == BIT_MODE_4){
		for (int i = 0; i<4; i++)
			digitalWrite(l->datapin[i], (val >> (i + 4)) & 0x01);

		digitalWrite(l->enable_pin, HIGH);
		digitalWrite(l->enable_pin, LOW);
	}

	for (int i = 0; i < l->bitmode; i++)
		digitalWrite(l->datapin[i], (val >> i) & 0x01);

	digitalWrite(l->enable_pin, HIGH);
	digitalWrite(l->enable_pin, LOW);
}

uint8_t lcd_getRaw(LCD *l, uint8_t rs_mode){
	digitalWrite(l->rs_pin, rs_mode);
	digitalWrite(l->rw_pin, HIGH);

	uint8_t retVal = 0;

	for (int i = 0; i < l->bitmode; i++){
		pinMode(l->datapin[i], INPUT);
		retVal |= (digitalRead(l->datapin[i]) << i);
		pinMode(l->datapin[i], OUTPUT);
	}

	if (l->bitmode == BIT_MODE_4){
		retVal <<= 4;

		digitalWrite(l->enable_pin, HIGH);
		digitalWrite(l->enable_pin, LOW);

		for (int i = 0; i < 4; i++){
			pinMode(l->datapin[i], INPUT);
			retVal |= (digitalRead(l->datapin[i]) << i);
			pinMode(l->datapin[i], OUTPUT);
		}
	}

	digitalWrite(l->enable_pin, HIGH);
	digitalWrite(l->enable_pin, LOW);

	return retVal;
}
